package com.itheima.controller;

import com.github.pagehelper.Page;
import com.itheima.domain.Student;
import com.itheima.service.StudentService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("student")
public class StudentController {

    //1.从注册中心获取studentService的url
    //2.rpc
    //3.结果封装一个代理对象，给变量赋值
    @Reference//远程注入
    private StudentService studentService;

    /*添加数据*/
    @RequestMapping("toAddStudent")
    public String toAdd(){
        return "add";
    }

    @RequestMapping("addStudent")
    public String add(Student student, Model model){
        int add = studentService.add(student);
        if(add == 0 ){
            model.addAttribute("msg","添加失败-----");
            return "error";
        }
        return "redirect:/list";
    }

    /*修改数据*/
    @RequestMapping("toUpdateStudent")
    public String toUpdate(Integer id,Model model){
        Student byId = studentService.findById(id);
        model.addAttribute("student",byId);
        return "edit";
    }

    @RequestMapping("updateStudent")
    public String update(Student student,Model model){
        int update = studentService.update(student);
        if(update == 0 ){
            model.addAttribute("msg","修改失败-----");
            return "error";
        }
        return "redirect:/list";
    }

    /*删除数据*/
    @DeleteMapping("deleteStudent")
    public String delete(Integer id,Model model){
        int delete = studentService.delete(id);
        if(delete == 0 ){
            model.addAttribute("msg","删除失败-----");
            return "error";
        }
        return "redirect:/list";
    }

    /*查看所有数据*/
    @RequestMapping("list")
    public String findPage(@RequestParam(defaultValue = "1")Integer page,
                           @RequestParam(defaultValue = "1")Integer size,Model model){
        Page<Student> all = studentService.findAll(page, size);
        int pages = all.getPages();

        //数据都放到request域中
        model.addAttribute("all",all);
        model.addAttribute("pages",pages);
        /*当前页*/
        model.addAttribute("currentPage",all.getPageNum());

        return "list";
    }

}
